package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * filter test
 */
@Slf4j
//@WebFilter(filterName = "loginCheck2",urlPatterns = "/*")
public class LoginCheckFilter2 implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取URI
        String requestURI = request.getRequestURI();

        //定义无需判断的uri
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };

        //定义方法解析uri
        boolean check = check(uris, requestURI);

        //判断是否需要处理
        if (check){
            //无需处理
            log.info("本次请求无需处理");
            filterChain.doFilter(request,response);
            return;
        }

        //判断登录状态
        if (request.getSession().getAttribute("employee") != null){
            //放行
            log.info("用户已登录");
            filterChain.doFilter(request,response);
            return;
        }

        //未登录
        log.info("请先登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }


    public boolean check(String[] uris, String requestURI){
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }


}
